<template>
  <a-modal :title="formTile + '颜色'" :visible="true" width="60%" :footer="null" @cancel="reset">
    <a-card>
      <a-row type="flex" justify="start" align="top">
        <a-col :span="24">
          <a-form :form="form" @submit="handleSubmit" :labelCol="formItemLayout.labelCol"
            :wrapperCol="formItemLayout.wrapperCol">
            <a-form-item label="颜色" :required="true">
              <a-select allow-clear show-search optionFilterProp="children" @search="getColors" placeholder="请选择颜色"
                @change="selectChange" v-decorator="[
                  'code',
                  {
                    rules: [{ required: true, message: '请选择颜色!' }],
                  },
                ]">
                <a-select-option :value="item.code" v-for="item in colors" :key="item.code">
                  {{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="是否是封面">
              <a-switch v-decorator="[
                'cover',
                { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '请选择' }] },
              ]"></a-switch>
            </a-form-item>
            <a-form-item label="图片" :required="true">
              <a-upload name="file" list-type="picture-card" :multiple="true" class="avatar-uploader"
                :data="{ type: 2, brand: brandName }" :action="uploadUrl" :fileList="fileList"
                :before-upload="beforeUpload" @change="handleChange" v-decorator="[
                  'url',
                  {
                    rules: [{ required: true, message: '请上传图片' }],
                  },
                ]">
                <div v-if="fileList.length <= 5">
                  <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-row>
              <a-col :span="16" :offset="8" class="info-action">
                <a-button type="primary" @click="reset">返回</a-button>
                <a-button type="primary" class="ml-20" html-type="submit" :loading="loading">保存</a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
  </a-modal>
</template>

<script>
import { postAction } from '@/api/manage'
import { pattern } from '@api/pattern/index'
import { currencyCreate, currencyUpdate, uploadUrl, getSystemPro, queryDetail, editionList, imgCreate, examineCheck } from '@api/pattern/index.js'
// import { getSystemPro, currencyCreate, currencyUpdate, queryDetail,currencyList } from '@api/pattern/index.js'
export default {
  components: {},

  props: {
    color: {
      type: Object,
      default: null
    },
    patternId: {
      type: [Number, String],
      default: ''
    },
    brandName: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      colors: [],
      ifCheck: 0,
      current: 1,
      size: 1000,
      total: 0,
      linkName: '',
      loading: false,
      fileds: [],
      uploading: false,
      templates: [],
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 16 },
          xs: { span: 16 },
          sm: { span: 16 }
        }
      },
      fileList: [],
      imageUrl: '',
      ifAdd: false,
      loading: false,
      record: null,
      pushType: undefined,
      formTile: '新增',
      uploadLoading: false,
      uploadUrl,
      colorName: ''
    }
  },

  computed: {
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    }
  },

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'category' })
  },

  created() {
    this.getColors()
    const { color } = this.$props
    console.log(color)
    if (color) {
      this.formTile = '编辑'
      this.colorName = color.name
      this.$nextTick(() => {
        console.log(color)
        const images = color.images
        if (Array.isArray(images) && images.length > 0) {
          this.fileList = images.map(item => {
            return {
              name: item.name,
              uid: item.url,
              dataId: item.dataId,
              status: 'done',
              url: item.url
            }
          })
          this.form.setFieldsValue({
            url: images.map(item => {
              return {
                name: item.name,
                url: item.url
              }
            })
          })
        }
        this.form.setFieldsValue({
          code: color.code,
          cover: color.cover == 1
        })
      })
    }
  },

  methods: {
    selectChange(e) {
      const color = this.colors.find(item => item.code == e)
      this.colorName = color.value || ''
      console.log(e, color)
    },
    async getColors(name) {
      try {
        const res = await getSystemPro('color', { name, size: 1000, current: 1 })
        this.colors = res.data
      } catch (error) {
        console
      }
    },
    handleChange(info) {
      let fileList = [...info.fileList]
      this.fileList = info.fileList
      if (info.file.status === 'uploading') {
        this.uploading = true
        return
      }
      if (info.file.status === 'done') {
        this.uploading = false
        let list = fileList.map(file => {
          if (file.response) {
            if (file.response.code == 200) {
              if (file.response.data.yidunSuggestion == 0) {
                file.dataId = file.response.data.dataId
              } else {
                let that = this
                that.$message.error(file.response.data.yidunExplain ? '该图案包含' + file.response.data.yidunExplain : '该图案包含敏感内容')
                file.status = 'error'
                // that.$confirm({
                //   content: file.response.data.yidunExplain ? '该图案包含' + file.response.data.yidunExplain + '要继续上传吗？' : '该图案包含敏感内容，要继续上传吗？',
                //   onOk: () => {
                //     file.dataId = file.response.data.dataId
                //   },
                //   onCancel() {
                //     that.fileList.pop()
                //   }
                // })
              }
              file.url = file.response.data.url
            } else {
              this.$message.error('图片上传失败')
              this.fileList.pop()
              return fileList
            }
          }
          return file
        })
        this.fileList = list.filter(file => file.status != 'error');
      }
      if (info.file.status === 'error') {
        this.$message.error('图片上传失败')
      }
    },

    beforeUpload: function (file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.setFieldsValue({
        url: this.fileList.map(item => {
          return {
            name: item.name,
            dataId: item.dataId ? item.dataId : '',
            url: item.url
          }
        })
      })
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log(values);
          this.tosubmit(values)
        }
      })
    },

    async addVersion(id) { },
    tosubmit(values) {
      const checkColor = {
        colorId: '',
        imageList: [],
        patternId: this.patternId,
        scene: this.color ? 5 : 6
      }
      postAction(`${pattern}pattern/examine/check`, checkColor).then(res => {
        if (res.code == 30000) {
          this.$message.error(res.msg)
          this.loading = false
        } else if (res.code != 200 && res.code != 30000) {
          this.$confirm({
            content: res.msg,
            onOk: () => {
              this.submit(values, 1)
            },
            onCancel: () => {
              this.reset()
            }
          })
        } else {
          this.submit(values, 2)
        }
      })
    },
    async submit(values, key) {
      console.log(values)
      try {
        this.loading = true
        const urls = values.url || []
        const { color, jobNumber, patternId, colorName: name } = this
        const colorParams = {
          patternId,
          jobNumber,
          name,
          cover: values.cover ? 1 : 0,
          code: values.code
        }
        if (color) {
          colorParams.id = color.id
        }
        var edition = color ? 1 : ''
        const FNCName = color ? currencyUpdate : currencyCreate
        const res = await FNCName('color', colorParams)
        if (res.code == 200) {
          const edtionType = edition ? editionList : currencyCreate
          const edtionParams = edition ? { colorId: res.data.id || color.id } : { jobNumber, patternColorId: res.data.id || color.id, name: `版本-${name}` }
          const version = await edtionType('edition', edtionParams)
          if (!version.data.id) {
            const newedtionParams = { jobNumber, patternColorId: res.data.id || color.id, name: `版本-${name}` }
            var newversion = await currencyCreate('edition', newedtionParams)
          }
          // 新增图片地址
          console.log(urls)
          const imageList = urls.map(item => {
            return item.url ? item.url : item.response.data.url
          })
          const images = urls.map(item => {
            return {
              name: item.name,
              dataId: item.dataId ? item.dataId : '',
              url: item.url ? item.url : item.response.data.url
            }
          })
          const params = {
            jobNumber,
            images,
            editionId: version.data.id ? version.data.id : newversion.data.id
          }
          try {
            postAction(`${pattern}imageUrl/batchSave`, params).then(res => {
              if (res.code == 200) {
                let text = color ? '编辑成功' : '新增成功'
                this.$message.success(text)
                this.reset()
              } else {
                this.$message.error(res.msg || res.message)
              }
            })
          } catch (error) {
            this.$message.error(error.msg)
          }
          if (key == 1) {
            const initParams = {
              colorId: this.color.id,
              patternId: this.patternId,
              scene: this.color?5:6,
              jobNumber: this.jobNumber
            }
            postAction(`${pattern}pattern/examine/init`, initParams).then(res => {
              if ((res.data = 200)) {
                this.$message.success('图案审核/批注状态已重置')
              }
            })
          }
        } else {
          this.$message.error(res.msg || res.message)
          this.loading = false
        }
      } catch (error) {
        this.$message.error(error.msg || '出错了')
        this.loading = false
      }
    },
    reset() {
      this.form.resetFields()
      this.loading = false
      this.fileList = []
      this.fileds = []
      // console.log(this.$emit);
      this.$emit('close')
    }
  }
}
</script>

<style scoped lang="less">
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}

.ml-20 {
  margin-left: 20px;
}

.poster {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  position: relative;

  &:hover {
    .img-modal {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .img {
    width: 100%;
    height: 100%;
  }

  .img-modal {
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
    position: absolute;
    color: #fff;
    font-size: 20px;
    width: 100%;
    top: 0;
    height: 100%;
    left: 0;
  }
}

.fileList {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
}
</style>